<template>
  <view class="login-box">
    <view class="main-box">
      <view>
        <img src="https://img.qumoyugo.com/webimgbg/pk_logo.png"  class="img" alt="">
      </view>
      <view class="login-com">
        <button type="default" v-if="checked" open-type="getPhoneNumber" @getphonenumber="getphonenumber" class="btn">
          手机号快捷登录
        </button>
        <view type="default" v-else @click="handlerTips" class="btn">
          手机号快捷登录
        </view>
      </view>
    </view>
    <view class="bottom">
      <!-- <label class="radio">
        <radio style="transform:scale(0.7)" :checked="checked" color="#000000" />
      </label> -->
      <label class="radio" @click="handlerClickRadio">
        <uni-icons :type="checked ? 'checkbox-filled':'circle'" size="20"></uni-icons>
      </label>
      <view>
        <text @click="checked = !checked">我已阅读并同意</text>
        <text @click="gotoPage(1)" style="color:#000000">《品客聚精彩用户协议》</text>和
        <text @click="gotoPage(2)" style="color:#000000">《隐私保护协议》</text>
      </view>
    </view>
  </view>
  <!-- <SelfToast content="请阅读并勾选下方《品客聚精彩用户协议》和《隐私保护协议》" ref="selfToast"></SelfToast> -->
  <view class="u-center-popupRef" v-if="popupRef">
    <view class="popup-toast">
      <view class="title">提示</view>
      <view class="">请阅读并勾选下方《品客聚精彩用户协议》和《隐私保护协议》</view>
    </view>
  </view>
  <template v-if="PLATFORM !== 'prod'">
    <view style="padding: 54rpx">
      <uni-easyinput trim="all" v-model="telNumber" placeholder="输入手机号"></uni-easyinput>
      <button @click="btnLogin" style="margin-top:40rpx" type="primary">注册品客聚精彩</button>
    </view>
  </template>
</template>

<script setup>
import { ref, getCurrentInstance, onBeforeUnmount } from 'vue'
import { useStore } from '@/store'
import { onLoad } from '@dcloudio/uni-app'
import { storage, urlGet } from '@/utils/utils'
import { TOKEN, REGISTER_FORM_MP, REGISTER_CUSTOMER_ID, REGISTER_HELP_SUCCESS, OPEN_ADD_PETS } from '@/assets/js/config.js'
// import { loginIM } from '@/assets/js/tencentIM/tencentIM.js'
const store = useStore()
const PLATFORM = ref(import.meta.env.VITE_APP_BASE_URL)
const { $https } = getCurrentInstance().appContext.config.globalProperties
const checked = ref(false)
const timer = ref(null)
const timerLogin = ref(null)
const popupRef = ref(false)
const gotoPage = (value) => {
  uni.navigateTo({
    url: value === 2 ? '/pages/privacy' : '/pages/concert'
  })
}
const redirectUrl = ref('')
const telNumber = ref()
onLoad((option) => {
  if (option.redirect) {
    redirectUrl.value = decodeURIComponent(decodeURIComponent(option.redirect))
  }
})
const handlerClickRadio = () => {
  checked.value = !checked.value
}
const handlerTips = () => {
  popupRef.value = true
  timerLogin.value = setTimeout(() => {
    popupRef.value = false
  }, 2000)
}
const getphonenumber = (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') return false
  if (!e.detail.code) { // 版本低下不能获取到信息
    uni.showModal({
      title: '提示',
      content: '微信版本太低请升级版本'
    })
    return false
  }
  wx.login({
    success: (loginRes) => {
      uni.showLoading({
        title: '登录中...'
      })
      $https({
        // 利用code去换取openid
        url: '/js-token',
        type: '',
        data: {
          code: loginRes.code,
          scene: 'mp4'
        }
      }).then(resOpenid => {
        if (resOpenid.code === 0) {
          const registerFrom = storage.get(REGISTER_FORM_MP)
          const recommendCustomerId = storage.get(REGISTER_CUSTOMER_ID)
          storage.remove(REGISTER_CUSTOMER_ID)
          storage.remove(REGISTER_FORM_MP)
          const data = {
            code: e.detail.code,
            type: 'wechat',
            registerPhoneType: 'MP',
            scene: 'mp4',
            openId: resOpenid.data.openid,
            recommendCustomerId
          }
          if (redirectUrl.value.indexOf('/events/eventsDetail') !== -1 && urlGet('share', redirectUrl.value)) {
            data.relationActivityId = urlGet('id', redirectUrl.value)
          }
          if (urlGet('entryType', redirectUrl.value)) {
            data.entryType = urlGet('entryType', redirectUrl.value)
          }
          if (registerFrom) {
            data.registerFrom = registerFrom
          }
          if (urlGet('relationActivityId', redirectUrl.value)) {
            data.relationActivityId = urlGet('relationActivityId', redirectUrl.value)
          }
          if (urlGet('activityOwnerId', redirectUrl.value)) {
            data.activityOwnerId = urlGet('activityOwnerId', redirectUrl.value)
          }
          // console.log(2223556, data)
          // 登录关联活动id
          $https({
            url: '/login',
            type: '',
            method: 'POST',
            data
          }).then(res => {
            if (res.code === 0) {
              storage.remove(REGISTER_FORM_MP)
              store.commit('setToken', res.data.token)
              storage.set(TOKEN, res.data.token)
              if (urlGet('entryType', redirectUrl.value) === '2') {
                storage.set(OPEN_ADD_PETS, true)
              }
              let url = ''
              if (res.data.hasCompleted) {
                url = decodeURIComponent(redirectUrl.value)
              } else {
                url = `/user/uploadAvatar?redirect=${encodeURIComponent(redirectUrl.value)}`
              }
              console.log('跳转url链接1', url)
              if (url.indexOf('/events/eventsDetail') !== -1 && urlGet('share', url) && +urlGet('rmd', url) !== res.data.customerId) {
                storage.set(REGISTER_HELP_SUCCESS, 1)
              }
              // 排除直接在此页面的情况
              if (!url || url.indexOf('/login') !== -1) {
                url = '/pages/index'
              }
              console.log('跳转url链接2', url)
              uni.hideLoading()
              // 如果有活动，登录成功及助力成功
              uni.redirectTo({
                url,
                fail: () => {
                  uni.switchTab({
                    url: url === '/' || !url ? '/pages/index' : url
                  })
                }
              })
              // 地图经纬网传递
              /* uni.authorize({
                scope: 'scope.userLocation',
                success: () => {
                  uni.getLocation({
                    type: 'gcj02', // 定位的坐标类型，'wgs84'表示 GPS 坐标，'gcj02'表示国测局坐标
                    altitude: false, // 是否获取高度信息
                    success: (res) => {
                      // 处理地理位置数据
                      $https({
                        url: '/app/geo',
                        type: '',
                        method: 'post',
                        data: { lat: res.latitude, lng: res.longitude }
                      })
                    },
                    fail: (err) => {
                      console.log('获取地理位置失败:', err)
                    }
                  })
                }
              }) */
              $https({
                url: '/profile',
                type: ''
              }).then(profile => {
                if (profile.code === 0) {
                  store.commit('setProfile', profile.data)
                  // const phone = profile.data.attr.phone
                  // const faceUrl = profile.data.attr.faceUrl
                  // const nickname = profile.data.attr.nickname
                  // console.log('IM登录', phone, faceUrl, nickname)
                  // loginIM(phone, faceUrl, nickname)
                }
              })
            }
          })
        }
      })
    }
  })
}
const btnLogin = () => {
  const recommendCustomerId = storage.get(REGISTER_CUSTOMER_ID)
  storage.remove(REGISTER_CUSTOMER_ID)
  const data = {
    account: `86-${telNumber.value}`,
    code: PLATFORM.value === 'sprint' ? '7777' : '0832',
    type: 'phone',
    registerPhoneType: 'MP',
    scene: 'mp4',
    entryType: urlGet('entryType', redirectUrl.value),
    relationActivityId: urlGet('relationActivityId', redirectUrl.value) || urlGet('id', redirectUrl.value),
    activityOwnerId: urlGet('activityOwnerId', redirectUrl.value)
  }
  if (recommendCustomerId) {
    data.recommendCustomerId = recommendCustomerId
  }
  $https({
    url: '/login',
    type: '',
    method: 'POST',
    data
  }).then(res => {
    if (res.code === 0) {
      store.commit('setToken', res.data.token)
      storage.set(TOKEN, res.data.token)
      storage.set(OPEN_ADD_PETS, true)
      let url = ''
      if (res.data.hasCompleted) {
        url = decodeURIComponent(redirectUrl.value)
      } else {
        url = `/user/uploadAvatar?redirect=${encodeURIComponent(redirectUrl.value)}`
      }
      console.log('跳转url链接1', url)
      if (url.indexOf('/events/eventsDetail') !== -1 && urlGet('share', url) && +urlGet('rmd', url) !== res.data.customerId) {
        storage.set(REGISTER_HELP_SUCCESS, 1)
      }
      // 排除直接在此页面的情况
      if (!url || url.indexOf('/login') !== -1) {
        url = '/pages/index'
      }
      console.log('跳转url链接2', url)
      // 如果有活动，登录成功及助力成功
      uni.redirectTo({
        url,
        fail: () => {
          uni.switchTab({
            url: url === '/' || !url ? '/pages/index' : url
          })
        }
      })
      $https({
        url: '/profile',
        type: ''
      }).then(profile => {
        if (profile.code === 0) {
          store.commit('setProfile', profile.data)
          // const phone = profile.data.attr.phone
          // const faceUrl = profile.data.attr.faceUrl
          // const nickname = profile.data.attr.nickname
          // console.log('IM登录', phone, faceUrl, nickname)
          // loginIM(phone, faceUrl, nickname)
        }
      })
    }
  })
}
onBeforeUnmount(() => {
  timer.value = null
  timerLogin.value = null
})
</script>

<style scoped lang="scss">
.login-box{
  padding: 64rpx 15rpx;
  height: 100vh;
  .main-box{
    .img{
      width: 718rpx;
      height: 546rpx;
    }
    .login-com{
      margin: 0 72rpx;
      .btn{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 84rpx;
        border-radius: 42rpx;
        background: #58AA46;
        color: #ffffff;
        margin-top: 90rpx;
        font-size: 32rpx;
        &:active{
          opacity: 0.8;
        }
      }
    }
  }
  .bottom{
    color: #999999;
    display: flex;
    margin: 40rpx 60rpx;
    font-size: 26rpx;
  }
}
.u-center-popupRef{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.popup-toast{
  width: 520rpx;
  padding: 20rpx 50rpx;
  background: rgba(0,0,0,0.8);
  border-radius: 12rpx;
  text-align: center;
  font-size: 28rpx;
  color: #ffffff;
  .title{
    font-size: 30rpx;
    height: 42rpx;
    line-height: 42rpx;
    margin-bottom: 14rpx;
  }
}
</style>
